'use strict';
const db = uniCloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  const { wallpaper_id } = event;
  
  try {
    // 验证壁纸ID
    if (!wallpaper_id || typeof wallpaper_id !== 'string') {
      return {
        code: 400,
        message: '壁纸ID无效'
      };
    }
    
    // 检查壁纸是否存在
    const wallpaperRes = await db.collection('wallpapers').doc(wallpaper_id).get();
    if (!wallpaperRes.data) {
      return {
        code: 404,
        message: '壁纸不存在'
      };
    }
    
    // 获取用户ID（如果已登录）
    let userId = null;
    if (event.uniIdToken) {
      try {
        const { uniID } = require('uni-id-common');
        const uniIDIns = uniID.createInstance({ context });
        const userInfo = await uniIDIns.checkToken(event.uniIdToken);
        if (userInfo.code === 0) {
          userId = userInfo.uid;
        }
      } catch (userError) {
        console.log('获取用户信息失败:', userError);
        // 不影响主流程，继续执行
      }
    }
    
    // 开始事务
    const transaction = await db.startTransaction();
    
    try {
      // 增加壁纸下载次数
      await transaction.collection('wallpapers').doc(wallpaper_id).update({
        data: {
          download_count: _.inc(1)
        }
      });
      
      // 如果用户已登录，记录下载历史
      if (userId) {
        await transaction.collection('downloads').add({
          user_id: userId,
          wallpaper_id: wallpaper_id,
          download_date: new Date()
        });
      }
      
      // 提交事务
      await transaction.commit();
      
      return {
        code: 0,
        message: '下载记录成功',
        data: {
          wallpaper_id: wallpaper_id,
          download_count: (wallpaperRes.data.download_count || 0) + 1
        }
      };
    } catch (error) {
      // 回滚事务
      await transaction.rollback();
      throw error;
    }
  } catch (error) {
    console.error('记录下载失败:', error);
    return {
      code: 500,
      message: '记录下载失败',
      error: error.message
    };
  }
};